<template>
  <div class="jnpf-content-wrapper h-full" v-loading="loading">
    <div class="jnpf-content-wrapper-left h-full left-tree">
      <BasicLeftTree
        title="分包或委托单位"
        ref="leftTreeRef"
        :treeData="treeData"
        :loading="treeLoading"
        @reload="reloadTree"
        @select="handleTreeSelect"
        showToolbar
      />
    </div>
    <div class="IlmsForm">
      <div class="IlmsForm-content">
        <div>
          <div class="tag-tip">
            <a-tag color="orange">请先选择"分包或委托单位"，再分配合同交付清单任务。</a-tag>
            <a-tag v-if="companySelectId" color="green">
              {{ `${companySelectName}-交付清单总额:【含税 ${formatPrice(taxTotalAmount)}】、【未税 ${formatPrice(untaxTotalAmount)}】` }}
            </a-tag>
          </div>
          <BasicTable
            ref="tableRef"
            :loading="loading"
            :immediate="false"
            :scroll="{ y: 'auto', x: '100%' }"
            :rowClassName="rowClassNameMethod"
            @register="registerTable"
            class="h-full"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'unitOfMeasurement'">
                <span>{{ record.childrenInfo ? '--' : record.unitOfMeasurement }}</span>
              </template>
              <template v-if="column.key === 'unitPrice'">
                <span>{{ record.childrenInfo ? '--' : formatPrice(record.unitPrice) }}</span>
              </template>
              <template v-if="column.key === 'taxRate'">
                <span>{{ record.childrenInfo ? '--' : formatPercent(record.taxRate) }}</span>
              </template>
              <template v-if="column.key === 'quantity'">
                <span>{{ record.childrenInfo ? '--' : record.quantity }}</span>
              </template>
              <template v-if="column.key === 'action'">
                <TableAction :actions="getTableActions(record)" />
              </template>
            </template>
          </BasicTable>
        </div>
      </div>
      <div v-if="isMine" class="IlmsForm-footer">
        <a-space>
          <a-button
            :loading="loading"
            v-if="current == 0"
            type="primary"
            @click="saveTasks"
          >下一步</a-button>
        </a-space>
      </div>
    </div>
  </div>
  
  <IlmsLayer
    title="子项数据"
    :area="['80%', '60%']"
    :z-index="1000"
    :shade-close="false"
    :show-cancel="false"
    confirm-text="关闭"
    v-model="dialogFormVisible" 
    @confirm="confirm"
    maxmin resize shade
  >
    <div class="p-3 h-full">
      <BasicTable 
        :loading="loading" 
        :immediate="false"
        @register="subItemTable"
      ></BasicTable>
    </div>
  </IlmsLayer>
</template>

<script name="deliveryList" setup>
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicLeftTree } from '@/components/Tree';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { formatPercent, formatPrice } from '@/utils/priceUtil';
  import { getCompanyOrBusinessUnitList } from '@/api/permission/organize'; // 公司单位接口
  import { tableOptions, resdata, tableList, columnsList } from '@/views/project/internalOperations/common/deliveryListConfig';
  import { getContractInfoByCode, savePackageCompanyUnit, getPackageTrustList } from '@/views/project/internalOperations/common/api'; 

  const emit = defineEmits(['initTasks']);
  const { createMessage, createWarningModal } = useMessage();
  const leftTreeRef = ref(), tableRef = ref();
  const loading = ref(false);
  const treeData = ref([]), 
        treeLoading = ref(false);
  const taskToCompanyMap = ref({});

  const taxTotalAmount = ref(0), // 对应公司所选的交付清单金额合计
        untaxTotalAmount = ref(0),
        contractDeliveryTableList = ref([]); // 合同交付清单数据

  const selfCompany = ref(''), // 合同签署乙方==本合同签署甲方
        companySelectId = ref(''),
        companySelectName = ref(''),
        companyTaskList = ref([]),
        selectedRowKeys = ref([]);

  const allocateData = ref({}), // 公司和任务分配所有信息(全部)
        historicalAllocationData = ref([]); // 历史公司和任务分配情况；
        
  // 接收父组件数据
  const current = inject('current');
  const signAType = inject('signAType'); // 合同甲方签署单位
  const signBType = inject('signBType'); // 合同乙方签署单位
  const isNewVersion = inject('isNewVersion');
  const projectInfo = inject('projectInfo');
  const isMine = inject('isMine');

  const onSelectChange = async (selectedKeys) => {
    // 过滤掉已被其他公司选择的任务
    const filteredKeys = selectedKeys.filter(key => {
      // 检查该任务是否已被其他公司选择
      const isAssignedToOtherCompany = companyTaskList.value.some(
        item => item.companyId !== companySelectId.value && item.taskIds.includes(key)
      );
      return !isAssignedToOtherCompany;
    });
    
    // 只更新当前公司的选择（使用过滤后的keys）
    selectedRowKeys.value = filteredKeys;
    
    // 更新companyTaskList
    // 判断companyTaskList是否有当前公司存在
    const existingIndex = companyTaskList.value.findIndex(
      item => item.companyId === companySelectId.value
    );
    
    if (existingIndex >= 0) {
      if (filteredKeys.length > 0) {
        // 更新现有公司的选择
        companyTaskList.value[existingIndex].taskIds = [...filteredKeys];
      } else {
        // 如果选择为空，移除该公司的记录
        companyTaskList.value.splice(existingIndex, 1);
      }
    } else if (filteredKeys.length > 0) {
      // 添加新公司的选择
      const newCompanyTask = {
        companyId: companySelectId.value,
        companySelectName: companySelectName.value,
        taskIds: [...filteredKeys],
      };
      companyTaskList.value.push(newCompanyTask);
    }
    await nextTick();
    calculateSelectedAmount();
    // console.log("1-任务分配情况", companyTaskList.value);
  };
  
  const deliveryListChoose = (record) => {
    let id = record.materialsCode;
    let lockStatus = record.lockStatus;
    // 先检查锁定状态
    if (lockStatus == 2) return true;
    // 如果没有选择公司，则禁用所有行
    if (!companySelectId.value) return true;
    
    // 检查该任务是否被当前公司选中
    const isSelectedByCurrentCompany = companyTaskList.value.some(
      item => item.companyId === companySelectId.value && item.taskIds.includes(id)
    );

    // 如果被当前公司选中，则不禁用（可操作）
    if (isSelectedByCurrentCompany) return false;
    
    // 检查是否被其他公司选中
    const isSelectedByOtherCompany = companyTaskList.value.some(
      item => item.companyId !== companySelectId.value && item.taskIds.includes(id)
    );

    return isSelectedByOtherCompany;
  };

  const rowSelection = computed(() => {
    // 非客户经理不显示勾选列
    if (!isMine.value) return undefined;
    return {
      onChange: onSelectChange,
      getCheckboxProps: (record) => ({
        disabled: deliveryListChoose(record)
      }),
    };
  });

  const [
    registerTable, 
      { 
        setSelectedRowKeys,
        setTableData
      }
    ] = useTable({
    columns: columnsList,
    rowSelection,
    rowKey: 'materialsCode',
    actionColumn: {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
    },
    ...tableOptions,
  });
  
  // 子项弹窗相关数据
  const childrenInfo = ref([]);
  const dialogFormVisible = ref(false);

  const [subItemTable] = useTable({
    columns: columnsList,
    dataSource: childrenInfo,
    ...tableOptions,
  });

  const confirm = () => {
    dialogFormVisible.value = false;
  };

  const viewClue = (info) => {
    childrenInfo.value = info;
    dialogFormVisible.value = true;
  };

  const getTableActions = (record) => {
    if (record.childrenInfo) {
      return [{
        label: '查看子项',
        onClick: () => viewClue(record.childrenInfo),
      }];
    }
    return [];
  };

  // 获取公司树数据的方法
  const reloadTree = async () => {
    try {
      treeLoading.value = true;
      let where = {
        queryType: 'companiesAndCenters',
        companyCode: selfCompany.value, // 主合同乙方code
      };
      const res = await getCompanyOrBusinessUnitList(where);
      treeData.value = res.data.list.map(item => ({
        ...item,
        // 子项为空，是否是叶子节点设置为true
        isLeaf: Array.isArray(item.children) && item.children.length === 0
      })).filter(item => 
        // 合同签署乙方==本合同签署甲方，不显示【不能分分配给自己，处理机构过滤掉】
        item.id != selfCompany.value
      );
    } finally {
      treeLoading.value = false;
    }
  };
  
  // 强制刷新表格
  const refreshTable = () => {
    if (tableRef.value) tableRef.value.reload();
  };

  const handleTreeSelect = async (value, node) => {
    companySelectId.value = value;
    companySelectName.value = node.fullName;
    // 切换公司，重置合计金额；
    taxTotalAmount.value = 0;
    untaxTotalAmount.value = 0;

    // 重置选中状态
    selectedRowKeys.value = [];

    // 如果有已保存的选择，则恢复
    const companyTasks = companyTaskList.value.find(item => 
      item.companyId === value
    );
    if (companyTasks) {
      selectedRowKeys.value = [...companyTasks.taskIds];
    }
    await nextTick();
    refreshTable();
    nextTick(calculateSelectedAmount);
  };
  
  const taskAllocation = async () => {
    // 检查是否所有任务都已分配
    // 历史已分配or已分配交付清单条数
    const totalTaskIdsLength = companyTaskList.value.reduce((total, item) => total + item.taskIds.length, 0);
    // 总交付清单条数
    const totalTaskCount = contractDeliveryTableList.value.length;

    // 分包委托标识：1-全分包委托，2-只部分分包
    // 甲方=1外部 or 甲方=2数为或智能、乙方-3分子公司，(只部分分包)；
    let type = (signAType.value==1||signAType.value==2)&&signBType.value==3 ? 2 : 1;

    // signBType：1-外部(部分分包)，2-数为或智能(全分包委托)，3-分子公司(部分分包委托)
    if (totalTaskIdsLength < totalTaskCount && signBType.value == '2') {
      createMessage.error('还有未分配的交付清单任务，请检查并完成所有任务分配后再继续！');
      return false;
    }else if(totalTaskIdsLength >= totalTaskCount && type == 2){
      createMessage.error('分子公司只能部分分包，至少要留一条交付清单任务！');
      return false;
    }else if(totalTaskIdsLength==0){
      createMessage.error('至少要分配一条交付清单任务，再继续！');
      return false;
    }
    return new Promise((resolve) => {
      createWarningModal({
        title: '分配确认：',
        content: '您确认要这样分配交付清单里的任务吗？',
        okText: '确认',
        cancelText: '取消',
        okCancel: true, // 确保显示确认和取消按钮
        onOk: async () => {
          try {
            // 获取当前交付清单的所有物料编码
            const validMaterialCodes = contractDeliveryTableList.value.map(
              item => item.materialsCode
            );
            let where = {
              packageTrustMaterialVos: companyTaskList.value.map(i => {
                // 过滤掉contractDeliveryTableList中不存在的物料编码
                const validTaskIds = i.taskIds.filter(taskId => 
                  validMaterialCodes.includes(taskId)
                );
                // 筛选出当前公司分配中被锁定的物料编码
                const lockMaterialsCode = validTaskIds.filter(taskId => {
                  const task = contractDeliveryTableList.value.find(
                    item => item.materialsCode === taskId
                  );
                  return task && task.lockStatus == 2;
                });
                return {
                  companyUnitCode: i.companyId,
                  materialsCode: validTaskIds, // 所有分配的物料编码（含锁定）
                  lockMaterialsCode // 单独存储锁定的物料编码
                };
              }).filter(item => item.materialsCode.length > 0), // 过滤掉物料为空的对象
              contractCode: unref(projectInfo).contractCode,
              type,
            };
            if(isNewVersion.value) where.opType = 2; // 变更需要传递
            // console.log("2.1-where-分配任务参数", where);
            let res = await savePackageCompanyUnit(where);
            // console.log("2.2-res-分配后的参数", res.data);
            if(res.code==200) {
              createMessage.success('交付清单任务分配成功！');
              // resolve(resdata); // 前端假数据
              resolve(res.data); // 返回保存后的数据
            }
          } catch (error) {
            resolve(false); // 保存失败
          }
        },
        onCancel: () => {
          resolve(false); // 用户取消
        },
      });
    })
  };

  const saveTasks = async() => {
    if(!isMine.value) return createMessage.warning('非项目的客户经理和项目经理，不得对合同进行分包委托！');
    const saveResult = await taskAllocation();
    if (saveResult) {
      current.value += 1;
      emit('initTasks');
    }
  };

  // 初始化companyTaskList，基于historicalAllocationData
  const initCompanyTaskList = async (info) => {
    companyTaskList.value = info.map(item => ({
      ...item,
      companySelectName: '',
    }));
    
    // 如果当前选择了公司，设置对应的选中项
    if (companySelectId.value) {
      const currentCompanyTasks = companyTaskList.value.find(item => 
        item.companyId === companySelectId.value
      );
      if (currentCompanyTasks) {
        selectedRowKeys.value = [...currentCompanyTasks.taskIds];
      }
    }
    
    // 处理回显勾选
    await nextTick();
    let selectedData = companyTaskList.value.flatMap(item => item.taskIds);
    setSelectedRowKeys(selectedData || []);
  };


  watch(
    () => historicalAllocationData.value,
    (val) => {
      if(val && val.length > 0) initCompanyTaskList(val);
    }, 
    { immediate: true },
  );

  watch(
    () => companySelectId.value,
    refreshTable,
  );

  watch(
    () => companyTaskList.value, 
    (newVal) => {
      const map = {};
      newVal.forEach(company => {
        company.taskIds.forEach(taskId => {
          map[taskId] = company.companyId;
        });
      });
      taskToCompanyMap.value = map;
    }, 
    { deep: true, immediate: true }
  );

  // 回显该合同的交付清单任务的分配情况；
  const getTaskAllocationStatus = async (data=null) => {
    loading.value = true;
    try {
      let info = data || (await getPackageTrustList(unref(projectInfo).contractCode))?.data;
      allocateData.value = info;
      selfCompany.value = info?.salesProjectContractVo?.contractSigningPartyB || '';
      // 委托公司、以及对应物料信息存在
      if(info.contractTrustVoList){
        const result = info.contractTrustVoList.map(item => {
          // 处理可能为null或undefined的contractMaterialsTrustVoList
          const materialsList = item.contractMaterialsTrustVoList || [];
          
          // 获取一级对象的materialsCode（考虑空数组情况）
          const taskIds = materialsList
            .filter(material => material?.parentId === "0") // 使用可选链防止material为null
            .map(material => material?.materialsCode) // 使用可选链
            .filter(code => code != null); // 过滤掉可能的undefined或null值
          
          return {
            companyId: item.deptId || '', // 处理deptId可能为空的情况
            taskIds: taskIds
          };
        }).filter(item => item.companyId || item.taskIds.length > 0); // 可选：过滤掉完全空的项目

        historicalAllocationData.value = historicalAllocationData.value.concat(result)
      }else{
        historicalAllocationData.value = []
      }
      // 分包公司、以及对应物料信息存在
      if(info.contractPackageVoList){
        const result = info.contractPackageVoList?.map(item => {
          return {
            companyId: item.contractSigningPartyBCode,
            taskIds: item.contractMaterialsPackageList
              ?.filter(material => material?.parentId === "0") // 处理contractMaterialsPackageList可能为null的情况
              ?.map(material => material?.materialsCode) ?? [] // 处理materialsCode可能不存在的情况
          };
        }) ?? []; // 处理contractPackageVoList可能为null或undefined的情况
        
        historicalAllocationData.value = historicalAllocationData.value.concat(result)
      }
      loading.value = false;
    }catch (error) {
      loading.value = false;
      console.error("获取任务分配状态出错:", error);
      throw error;
    }
  };

  // 合计当前选中项的金额合计
  const calculateSelectedAmount = () => {
    let taxTotal = 0;
    let untaxTotal = 0;
    
    // 获取表格所有数据
    contractDeliveryTableList.value.forEach(item => {
      // 检查是否是当前公司选中的项
      const isSelected = selectedRowKeys.value.includes(item.materialsCode) && 
                        taskToCompanyMap.value[item.materialsCode] === companySelectId.value;
      
      if (isSelected) {
        taxTotal += parseFloat(item.taxTotalAmount) || 0;
        untaxTotal += parseFloat(item.untaxTotalAmount) || 0;
      }
    });
    
    // 更新金额显示
    taxTotalAmount.value = taxTotal;
    untaxTotalAmount.value = untaxTotal;
  };

  const initTable = async() => {
    const { contractCode } = projectInfo.value;
    if(!contractCode) return;
    // 合同code获取合同交付清单信息（有合同就一定有交付清单数据）；
    const contractRes = await getContractInfoByCode(contractCode);
    let info = contractRes?.data;
    signBType.value = info.signBType;
    if(info && info?.contractMaterials){
      contractDeliveryTableList.value = info?.contractMaterials
      // .filter(item => item.lockStatus != 2) // 先过滤掉外层lockStatus为2的项【历史分配里已经收入确认的数据】
      .map(item => {
        const newItem = item;
        // 如果原对象有children属性，则重命名为childrenInfo
        if (newItem.children) {
          newItem.childrenInfo = newItem.children.map(subitem => {
            const newSubitem = subitem;
            return newSubitem;
          });
          delete newItem.children; // 删除原来的children属性
        }
        return newItem;
      });
      // 前端假数据
      // contractDeliveryTableList.value = tableList.value;
      setTableData(contractDeliveryTableList.value || []);
      // 清空历史分配数据
      historicalAllocationData.value = [];
      await getTaskAllocationStatus();
      reloadTree();
    }else{
      createMessage.warning('该合同信息不存在合同交付清单！请重新选择合同信息。');
    }
    await nextTick();
    calculateSelectedAmount();
  };

  // 表格行背景样式
  const rowClassNameMethod = (record) => {
    if (!companySelectId.value) return '';
    const taskId = record.materialsCode;
    
    if (
      selectedRowKeys.value.includes(taskId) && 
      taskToCompanyMap.value[taskId] == companySelectId.value
    ) {
      return 'table-striped';
    }
    return '';
  };

  defineExpose({
    initTable,
    saveTasks,
  });
</script>

<style scoped>
  @import url('@/design/IlmsForm.less');
  /* 勾选背景色重置为白色 */
  :deep(.jnpf-basic-table .ant-table .ant-table-tbody > tr.ant-table-row-selected td) {
    background-color: #fff;
  }

  :deep(.table-striped) td {
    background-color: #e4f2ff !important;
  }

  .left-tree{
    margin-left: 15px;
  }

  .tag-tip {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
  }

  .IlmsForm-footer{
    border-top: 0px;
  }
</style>
